package com.tulele.vtool.task.async;

import com.tulele.vtool.model.*;
import com.tulele.vtool.model.combinedEntity.CurDayNewLookStatisInfo;
import com.tulele.vtool.service.INewLookArticleCountInfoService;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.SysGzhService;
import com.tulele.vtool.service.UserGroupGzhService;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.utils.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@Slf4j
public class LookPunchClockArticleAsyncTask {

//    @Autowired
//    private WeixinService weixinService;

//    @Autowired
//    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IUserInfoService userInfoService;

//    @Autowired
//    private PlatformSysInfoConfig platformSysInfoConfig;

    @Autowired
    private UserGroupGzhService userGroupGzhService;

    @Autowired
    private INewLookArticleCountInfoService newLookArticleCountInfoService;

    /**
     * 发送打卡文章被查看的微信公众号通知
     * @param userId  查看文章的用户ID
     * @param otherId 被查看的用户ID -- 也是微信通知的接受者
     * @param punchClockArticleInfo
     * @param lookUserNickName
     */
    @Async
    public void sendUserPunchClockArticleBeLookedWxPushMsg(Integer userId, Integer otherId, PunchClockArticleInfo punchClockArticleInfo, String lookUserNickName,String springProfilesActive) throws Exception {

        //发送微信公众号通知
        String userOpenId = userInfoService.getUserOpenId(otherId);


        //region （公众号做通）20210902
        UserGroupOpenId ugoId= userGroupGzhService.getUserOpenId(springProfilesActive,otherId);
        if(ugoId!=null){
            userOpenId=ugoId.getOpenId();
        }
        //endregion

        if (StringUtils.isNotBlank(userOpenId)) {

            PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

            int notifySwitchStatus = 1;

            WxNotifyMsgSetInfo wxNotifyMsgSetInfo = userInfoService.getUserNotifySetInfo(otherId);
            if (wxNotifyMsgSetInfo != null) {
                notifySwitchStatus = Optional.ofNullable(wxNotifyMsgSetInfo.getNotifySwitchStatus()).orElse(1);
            }

            //0-关闭提醒 1-立即提醒 2-15分钟内只提醒一次 3-1小时之内只提醒一次 4-3小时之内只提醒一次
            if (notifySwitchStatus == 0) {
                return;
            }

            //夜间勿扰状态 0-关闭（可以接受消息） 1-打开（夜间不接受消息）
            int nightDisturbStatus = 1;
            if (wxNotifyMsgSetInfo != null) {
                nightDisturbStatus = Optional.ofNullable(wxNotifyMsgSetInfo.getNightDisturbStatus()).orElse(1);
            }

            if (ToolUtil.getNightTimePeriodStatus() && nightDisturbStatus == 1) {
                return;
            }

            //如果不是即时推送类型并且上一次推送时间距离现在只有2分钟，则不推送
            Object userLastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
            if (userLastWxPushTimeObj != null) {
                String userLastWxPushTimeStr = (String)userLastWxPushTimeObj;

                int minuteDiff = DateUtil.getTimeDiff(2, userLastWxPushTimeStr);

                if (notifySwitchStatus > 1 && minuteDiff <= 2) {

                    return;

                }

            }

            //如果是即时推送类型，则只有是同一篇文章被查看了，才做2分钟限制
            Object instantLastWxPushTimeObj = redisCacheUtil.getCacheObject(userId + "instantLastWxPushTime" + otherId + "2articleId" + punchClockArticleInfo.getId());
            if (instantLastWxPushTimeObj != null) {

                String instantLastWxPushTimeStr = (String)instantLastWxPushTimeObj;

                int minuteDiff = DateUtil.getTimeDiff(2, instantLastWxPushTimeStr);

                if (notifySwitchStatus == 1 && minuteDiff <= 2) {

                    return;

                }
            }

            if (notifySwitchStatus == 2) {

                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    String lastWxPushTimeStr = (String)lastWxPushTimeObj;

                    int minuteDiff = DateUtil.getTimeDiff(2, lastWxPushTimeStr);

                    if (minuteDiff < 15) {

                        return;

                    }

                }

            }

            if (notifySwitchStatus == 3) {

                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    String lastWxPushTimeStr = (String)lastWxPushTimeObj;

                    int hourDiff = DateUtil.getTimeDiff(3, lastWxPushTimeStr);

                    if (hourDiff < 1) {

                        return;

                    }

                }

            }

            if (notifySwitchStatus == 4) {

                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    String lastWxPushTimeStr = (String)lastWxPushTimeObj;

                    int hourDiff = DateUtil.getTimeDiff(3, lastWxPushTimeStr);

                    if (hourDiff < 3) {

                        return;

                    }

                }

            }

            //可以发送之后，直接先设置最后推送时间，避免多个人同时查看时，多次推送
            redisCacheUtil.setCacheObject("lastWxPushTime" + otherId, DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss", DateUtil.getCurDate()), 86400);

            String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", punchClockArticleInfo.getClockArticleTime());
            String articleTitle = "";
            int clockArticleTimeType = Optional.ofNullable(punchClockArticleInfo.getClockArticleTimeType()).orElse(1);
            if (clockArticleTimeType == 1) {
                articleTitle = "早安正能量 " + formatDate;
            } else {
                articleTitle = "晚安正能量 " + formatDate;
            }

            String kefuMsg = String.format(SysConstant.NEW_USER_LOOK_ARTICLE_INFO_PUSH_A_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain()), articleTitle);
            int vipStatus = Optional.ofNullable(userInfoService.getUserVipStatus(otherId)).orElse(0);
            if (vipStatus == 1) {
                kefuMsg = String.format(SysConstant.NEW_USER_LOOK_ARTICLE_INFO_PUSH_B_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain()), lookUserNickName, articleTitle);
            }

            if (notifySwitchStatus == 1) {

                redisCacheUtil.setCacheObject(userId + "instantLastWxPushTime" + otherId + "2articleId" + punchClockArticleInfo.getId(), DateUtil.getFormatDate("yyyy-MM-dd HH:mm:ss", DateUtil.getCurDate()), 86400);

            } else if (notifySwitchStatus == 2 || notifySwitchStatus == 3 || notifySwitchStatus == 4) {

                CurDayNewLookStatisInfo curDayNewLookStatisInfo = newLookArticleCountInfoService.getCurDayNewLookStatisInfo(otherId);
                if (curDayNewLookStatisInfo != null) {

                    int lookUserCount = Optional.ofNullable(curDayNewLookStatisInfo.getLookUserCount()).orElse(0);
                    int lookCount = Optional.ofNullable(curDayNewLookStatisInfo.getLookCount()).orElse(0);

                    if (lookUserCount > 0 && lookCount > 0) {
                        kefuMsg = String.format(SysConstant.NEW_USER_LOOK_ARTICLE_SUMMARY_INFO_PUSH_B_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain()), lookUserCount, lookCount);
                    } else {
                        kefuMsg = SysConstant.NEW_USER_LOOK_ARTICLE_SUMMARY_INFO_PUSH_A_MSG.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain());
                    }
                }


            }

            Integer lookArticleInfoWxMsgPushTimes = processLookArticleInfoWxMsgPushTimes(otherId);
            if (lookArticleInfoWxMsgPushTimes%10 == 0) {

                kefuMsg = SysConstant.WX_USER_WX_MSG_PUSH_BEYONGD_LIMIT_PUSH_MSG.replace("[count]",lookArticleInfoWxMsgPushTimes.toString());;
                kefuMsg=kefuMsg.replace(SysConstant.frontDomain,platformSysInfoConfig.getFrontDomain());
            } else {

                String lastWxPushTimeStr = "";
                Object lastWxPushTimeObj = redisCacheUtil.getCacheObject("lastWxPushTime" + otherId);
                if (lastWxPushTimeObj != null) {
                    lastWxPushTimeStr = (String)lastWxPushTimeObj;
                }
                log.info("[" + otherId + "notifySwitchStatus] = " + notifySwitchStatus + " [lastWxPushTimeStr] = " + lastWxPushTimeStr);

            }

            UserInfo userInfo = userInfoService.getUserBaseInfoByOpenId(userOpenId);
            if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                kefuMsg =ToolUtil.handleMsgmenuidByIOS(kefuMsg);
            }

            WxMpKefuMessage message=WxMpKefuMessage.TEXT().toUser(userOpenId).content(kefuMsg).build();
            try {
                weixinService.getKefuService().sendKefuMessage(message);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 处理文章查看推送次数 24小时之内，查看文章推送次数计数，超过10次则不推送
     * @param userId
     */
    private int processLookArticleInfoWxMsgPushTimes(Integer userId) {

        Integer lookArticleWxPushTimes = (Integer)redisCacheUtil.getCacheObject(userId + "lookArticleWxPushTimes");

        if (lookArticleWxPushTimes == null) {
            lookArticleWxPushTimes = 1;
        }

        int finalLookArticleWxPushTimes = lookArticleWxPushTimes + 1;
        redisCacheUtil.setCacheObject(userId + "lookArticleWxPushTimes", finalLookArticleWxPushTimes, 86400);

        return finalLookArticleWxPushTimes;
    }

}
